<?php
namespace  Backend\Model;
use Think\Model;

class  AdsenseModel extends  Model
{


    // 定义表单验证的规则
    protected $_validate = array(
        //array('media_id', 'require', '必须要选择一个主分类！', 1),
        array('code_name', 'require', '广告位名称不能为空！', 1),
        array('code_name', '', '广告位名称已存在！', 0, 'unique', 3),
        array('width', 'require', '代码位尺寸不能为空！', 1),
        array('height', 'require', '代码位尺寸不能为空！', 1),
        array('width', 'number', '代码位尺寸必须是数字！', 1),
        array('height', 'number', '代码位尺寸必须是数字！', 1),

    );

    public function get_adsense($pageSize = 10) {

        $where = array('a.user_id' =>$_SESSION['id']);
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/

        $data['data'] = $this->alias('a')
            ->field('a.id,a.code_name,a.code_type,a.status,a.update_time,a.complement,b.apply_name,b.access_mode,sum(c.use_amount ) as use_amount')
            ->where($where)
            ->join('dsp_apply as b  on a.apply_id = b.id','LEFT')
            ->join('dsp_ad_delivery as c  on a.id = c.code_id','LEFT')
            ->group('a.id')
            ->order('a.id desc')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        return $data;
    }

    public function get_report($pageSize = 10) {


        $where = array('a.user_id' =>$_SESSION['id']);
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/

        $data['data'] = $this->alias('a')
            ->field('a.update_time,a.date_time,a.code_name,a.code_type,a.id,a.apply_id,a.status,b.apply_name')
            ->join('dsp_apply as b  on a.apply_id = b.id','LEFT')
            ->where($where)
            ->order('a.id desc')
            ->group('a.id')
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        return $data;
    }

    // 添加前
    protected function _before_insert(&$data) {
        $data['update_time']=time();
        $data['date_time'] =date('Y-m-d',time());
        $data['user_id'] =$_SESSION['id'];
    }

    // 修改前
    protected function _before_update(&$data) {
        $data['update_time']=time();
    }
}